package com.example.testapp.ui.mine

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.util.DisplayMetrics
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.NonNull
import com.example.testapp.R
import com.example.testapp.config.ApiProviderManager

/**
 * API配置对话框
 */
class ApiConfigDialog(context: Context, private val title: String, private val isImageApi: Boolean = true) : Dialog(context) {
    
    // UI控件
    private lateinit var tvDialogTitle: TextView
    private lateinit var etServiceProvider: EditText
    private lateinit var etApiUrl: EditText
    private lateinit var etApiKey: EditText
    private lateinit var btnCancel: Button
    private lateinit var btnConfirm: Button
    
    // 确认按钮点击监听器
    private var confirmListener: OnApiConfigConfirmListener? = null
    
    // 预先加载的配置值
    private var preloadedProvider: String = ""
    private var preloadedUrl: String = ""
    private var preloadedKey: String = ""
    
    // 当前选择的服务提供商
    private var selectedProvider: String = ""
    
    /**
     * 设置预加载的配置数据
     * @param provider 服务提供商
     * @param url API地址
     * @param key API密钥
     */
    fun setPreloadedConfig(provider: String?, url: String?, key: String?) {
        preloadedProvider = provider ?: ""
        preloadedUrl = url ?: ""
        preloadedKey = key ?: ""
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 去除默认标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        
        // 设置对话框背景透明
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        
        // 加载自定义布局
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_api_config, null)
        setContentView(view)
        
        // 初始化控件
        initViews()
        
        // 预加载配置数据
        preloadConfig()
        
        // 设置监听器
        setupListeners()
        
        // 设置对话框标题
        tvDialogTitle.text = title
        
        // 设置对话框宽度为屏幕宽度的80%
        setDialogWidth()
    }
    
    /**
     * 设置对话框宽度为屏幕宽度的80%
     */
    private fun setDialogWidth() {
        window?.let { window ->
            val displayMetrics = DisplayMetrics()
            window.windowManager.defaultDisplay.getMetrics(displayMetrics)
            val width = (displayMetrics.widthPixels * 0.8f).toInt()
            val layoutParams = WindowManager.LayoutParams()
            layoutParams.copyFrom(window.attributes)
            layoutParams.width = width
            window.attributes = layoutParams
        }
    }
    
    /**
     * 初始化控件
     */
    private fun initViews() {
        tvDialogTitle = findViewById(R.id.tv_dialog_title)
        etServiceProvider = findViewById(R.id.et_service_provider)
        etApiUrl = findViewById(R.id.et_api_url)
        etApiKey = findViewById(R.id.et_api_key)
        btnCancel = findViewById(R.id.btn_cancel)
        btnConfirm = findViewById(R.id.btn_confirm)
    }
    
    /**
     * 预加载配置数据到UI
     */
    private fun preloadConfig() {
        if (preloadedProvider.isNotEmpty()) {
            selectedProvider = preloadedProvider
            etServiceProvider.setText(selectedProvider)
            
            // 根据是否是预设提供商设置URL编辑状态
            if (ApiProviderManager.isPresetProvider(preloadedProvider)) {
                etApiUrl.isEnabled = false
                etApiUrl.background = context.getDrawable(R.drawable.edit_text_background_disabled)
                etApiUrl.hint = "预设API地址 (不可编辑)"
            } else {
                etApiUrl.isEnabled = true
                etApiUrl.background = context.getDrawable(R.drawable.edit_text_background)
                etApiUrl.hint = "请输入API地址"
            }
        }
        
        if (preloadedUrl.isNotEmpty()) {
            etApiUrl.setText(preloadedUrl)
        }
        
        if (preloadedKey.isNotEmpty()) {
            etApiKey.setText(preloadedKey)
        }
    }
    
    /**
     * 设置监听器
     */
    private fun setupListeners() {
        // 服务提供商选择
        etServiceProvider.setOnClickListener { showProviderPicker() }
        
        // 取消按钮点击事件
        btnCancel.setOnClickListener {
            dismiss()
        }
        
        // 确认按钮点击事件
        btnConfirm.setOnClickListener {
            confirmListener?.let { listener ->
                // 获取API URL和Key
                val apiUrl = etApiUrl.text.toString().trim()
                val apiKey = etApiKey.text.toString().trim()
                
                // 如果选择了预设提供商但URL为空，自动获取URL
                val finalApiUrl = if (ApiProviderManager.isPresetProvider(selectedProvider) && apiUrl.isEmpty()) {
                    ApiProviderManager.getApiUrl(selectedProvider) ?: ""
                } else {
                    apiUrl
                }
                
                // 调用回调接口
                listener.onConfirm(selectedProvider, finalApiUrl, apiKey)
            }
            dismiss()
        }
    }
    
    /**
     * 显示底部弹出的提供商选择器
     */
    private fun showProviderPicker() {
        // 获取提供商列表
        val providers = if (isImageApi) 
            ApiProviderManager.getImageApiProviders() 
        else 
            ApiProviderManager.getAiApiProviders()
        
        // 创建并显示底部弹出选择器
        val pickerDialog = ProviderPickerDialog(
            context, 
            providers, 
            "选择服务提供商"
        )
        
        // 预选中当前值
        if (selectedProvider.isNotEmpty()) {
            pickerDialog.preSelectProvider(selectedProvider)
        }
        
        // 设置选择监听器
        pickerDialog.setOnProviderSelectedListener { provider, apiUrl ->
            selectedProvider = provider
            etServiceProvider.setText(provider)
            
            // 如果提供了API地址，自动填充
            if (!apiUrl.isNullOrEmpty()) {
                etApiUrl.setText(apiUrl)
                
                // 如果是预设提供商，禁用编辑
                if (ApiProviderManager.isPresetProvider(provider)) {
                    etApiUrl.isEnabled = false
                    etApiUrl.background = context.getDrawable(R.drawable.edit_text_background_disabled)
                    etApiUrl.hint = "预设API地址 (不可编辑)"
                } else {
                    etApiUrl.isEnabled = true
                    etApiUrl.background = context.getDrawable(R.drawable.edit_text_background)
                    etApiUrl.hint = "请输入API地址"
                }
            } else {
                // 处理没有API地址的情况
                handleProviderSelection(provider)
            }
        }
        
        // 显示选择器
        pickerDialog.show()
    }
    
    /**
     * 处理服务提供商选择
     * @param provider 选择的提供商
     */
    private fun handleProviderSelection(provider: String) {
        if (provider == "自定义") {
            // 选择"自定义"时，清空API URL以允许用户输入
            etApiUrl.setText("")
            etApiUrl.isEnabled = true
            etApiUrl.background = context.getDrawable(R.drawable.edit_text_background)
            etApiUrl.hint = "请输入API地址"
        } else {
            // 从预设列表中选择时，自动填充API URL
            val apiUrl = ApiProviderManager.getApiUrl(provider) ?: ""
            if (apiUrl.isNotEmpty()) {
                etApiUrl.setText(apiUrl)
                etApiUrl.isEnabled = false  // 预设URL不允许编辑
                etApiUrl.background = context.getDrawable(R.drawable.edit_text_background_disabled)
                etApiUrl.hint = "预设API地址 (不可编辑)"
            } else {
                // 如果选择的不是预设提供商，启用URL编辑
                etApiUrl.isEnabled = true
                etApiUrl.background = context.getDrawable(R.drawable.edit_text_background)
                etApiUrl.hint = "请输入API地址"
            }
        }
    }
    
    /**
     * 设置确认按钮点击监听器
     */
    fun setOnApiConfigConfirmListener(listener: OnApiConfigConfirmListener) {
        this.confirmListener = listener
    }
    
    /**
     * 使用Kotlin函数类型简化接口
     */
    fun setOnApiConfigConfirmListener(listener: (serviceProvider: String, apiUrl: String, apiKey: String) -> Unit) {
        this.confirmListener = object : OnApiConfigConfirmListener {
            override fun onConfirm(serviceProvider: String, apiUrl: String, apiKey: String) {
                listener(serviceProvider, apiUrl, apiKey)
            }
        }
    }
    
    /**
     * API配置确认监听器接口
     */
    interface OnApiConfigConfirmListener {
        /**
         * 当用户点击确认按钮时回调
         * @param serviceProvider 服务提供方
         * @param apiUrl API地址
         * @param apiKey API密钥
         */
        fun onConfirm(serviceProvider: String, apiUrl: String, apiKey: String)
    }
} 